//
//  CookBookTopicViewController.m
//  Delicious2
//
//  Created by dllo on 16/1/8.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "CookBookTopicViewController.h"
#import "UMSocial.h"
@interface CookBookTopicViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) MBProgressHUD *HUD;

@property (nonatomic, assign) BOOL isSave;
@property (nonatomic, copy) NSString *kind;
@property (nonatomic, strong) UIBarButtonItem *item1;
@property (nonatomic, strong) UIBarButtonItem *item2;
@property (nonatomic, strong) UIBarButtonItem *item3;

@end

@implementation CookBookTopicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"专题";
    self.kind = @"食谱";
    self.isSave = NO;
    //    左右添加分享 收藏按钮
    self.item1 = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"FenxiangImage"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(rightFenxiangButtonDidPress:)];
    
    self.item2 = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"SaveImage"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(rightSaveButtonDidPress:)];
    
    self.item3 = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"HaveSaveImage"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(rightHaveSaveButtonDidPress:)];

    [self getData];
    [self creatCollectionView];
    
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"正在加载";
}


#pragma mark - creatCollecTionView
- (void)creatCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.itemSize = CGSizeMake(WIDTH , HEIGHT - 113);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.pagingEnabled = YES;
    
    [_collectionView registerClass:[CookTopicCustomCollectionViewCell class] forCellWithReuseIdentifier:@"CookTopicCustomCollectionViewCellIdentifier"];
    
    
    self.collectionView.bounces = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_collectionView];

}


#pragma maek - collectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CookTopicCustomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CookTopicCustomCollectionViewCellIdentifier" forIndexPath:indexPath];
    CookTopicModel *topicModel = self.dataSource[indexPath.item];
    cell.topicModel = topicModel;
    return cell;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self selectDataBaseHandle];
}

#pragma mark - buttonDidPress
//查看详情按钮点击事件
- (void)buttonTopicDidPress:(UIButton *)button {
    
    //获取对应页食物
    NSInteger n = self.collectionView.contentOffset.x / WIDTH;
    CookTopicModel *topicModel = self.dataSource[n];
    //跳转详情页面
    CookDetailsViewController *detailsVC = [[CookDetailsViewController alloc] init];
//    detailsVC.strTilte = topicModel.food_name;
    detailsVC.strCode = topicModel.food_code;
    
    [self.navigationController pushViewController:detailsVC animated:YES];
}

//已经收藏按钮点击事件
- (void)rightHaveSaveButtonDidPress:(UIButton *)button {
    
    if (self.dataSource.count != 0) {
        NSInteger item = self.collectionView.contentOffset.x / WIDTH;
        CookTopicModel *topicModel = self.dataSource[item];
        
        DataBaseHandle *dataBaseHandle = [DataBaseHandle shareDataBase];
        [dataBaseHandle openDataBase];
        [dataBaseHandle deleteDataBase:topicModel.food_name];
        self.navigationItem.rightBarButtonItems = @[self.item2, self.item1];
        [dataBaseHandle closeDataBase];
        
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        HUD.mode = MBProgressHUDModeText;
        HUD.margin = 10;
        HUD.cornerRadius = 3;
        HUD.labelText = @"取消收藏";
        [HUD hide:YES afterDelay:1];
    }
}
//收藏按钮点击事件
- (void)rightSaveButtonDidPress:(UIButton *)button {
    //数组保护
    if (self.dataSource.count != 0) {
        NSInteger item = self.collectionView.contentOffset.x / WIDTH;
        CookTopicModel *topicModel = self.dataSource[item];
        
        DataBaseHandle *dataBaseHandle = [DataBaseHandle shareDataBase];
        [dataBaseHandle openDataBase];
        [dataBaseHandle insertDataBase:topicModel.food_name withImage:topicModel.image_url withURL:topicModel.page_url withKind:self.kind];
        self.navigationItem.rightBarButtonItems = @[self.item3, self.item1];
        [dataBaseHandle closeDataBase];
        
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        HUD.mode = MBProgressHUDModeText;
        HUD.margin = 10;
        HUD.cornerRadius = 3;
        HUD.labelText = @"收藏成功";
        [HUD hide:YES afterDelay:1];
    }
}
//分享按钮点击事件
- (void)rightFenxiangButtonDidPress:(UIButton *)button {
    NSInteger item = self.collectionView.contentOffset.x / WIDTH;
    CookTopicModel *topicModel = self.dataSource[item];
    NSString *str = [[topicModel.food_code stringByAppendingString:@"       "] stringByAppendingString:topicModel.page_url];
    
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"507fcab25270157b37000010" shareText: str shareImage:nil shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent, nil] delegate:nil];
}

//查询数据库
- (void)selectDataBaseHandle {
    //数组保护
    if (self.dataSource.count != 0) {
        NSInteger item = self.collectionView.contentOffset.x / WIDTH;
        CookTopicModel *topicModel = self.dataSource[item];
        DataBaseHandle *dataBaseHandle = [DataBaseHandle shareDataBase];
        [dataBaseHandle openDataBase];
        [dataBaseHandle createTable];
        NSArray *array = [dataBaseHandle selectDataBase:nil];
        for (NSDictionary *dic in array) {
            // 判断是否已经收藏
            if ([dic[@"title"] isEqualToString:topicModel.food_name] && [dic[@"url"] isEqualToString:topicModel.page_url]) {
                self.isSave = YES;
                break;
            } else {
                self.isSave = NO;
            }
        }
        
        if (self.isSave) {
            self.navigationItem.rightBarButtonItems = @[self.item3, self.item1];
        } else {
            self.navigationItem.rightBarButtonItems = @[self.item2, self.item1];
        }
        
        [dataBaseHandle closeDataBase];
    }
}

#pragma mark - 获取数据
- (void)getData {
    
    NSString *strUrl = [[kCookBookGETURL stringByAppendingString:@"/"] stringByAppendingString:self.strId];
    [FSDNetWorkTool getWithURL:strUrl withParameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        NSArray *arr = result[@"topic"][@"pages"];
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dic in arr) {
            CookTopicModel *topicModel = [[CookTopicModel alloc] initWithDictionary:dic];
            [array addObject:topicModel];
        }
        self.dataSource = [NSArray arrayWithArray:array];
        
        self.HUD.hidden = YES;
        [self.collectionView reloadData];
        
        //查看详情按钮
        UIButton *buttonTopic = [UIButton buttonWithType:UIButtonTypeSystem];
        buttonTopic.frame = CGRectMake(WIDTH / 2 - 75, HEIGHT - self.tabBarController.tabBar.frame.size.height - 50, 150, 50);
        [buttonTopic setTitle:@"查看详情" forState:UIControlStateNormal];
        [buttonTopic setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        buttonTopic.backgroundColor = [UIColor blackColor];
        buttonTopic.titleLabel.font = [UIFont boldSystemFontOfSize:25];
        buttonTopic.layer.cornerRadius = 25;
        buttonTopic.alpha = 0.4;
        
        [buttonTopic addTarget:self action:@selector(buttonTopicDidPress:) forControlEvents:UIControlEventTouchUpInside];
        //没有网络则不添加
        Reachability *reach = [Reachability reachabilityWithHostname:@"www.apple.com"];
        if (reach.isReachable) {
            [self.view addSubview:buttonTopic];
        }
        
        [self selectDataBaseHandle];
    } fail:^(NSError *error) {
        NSLog(@"错误");
        
        self.HUD.labelText = @"加载失败";
        [self.HUD hide:YES afterDelay:3];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self selectDataBaseHandle];
    [self.collectionView nightMode];
    [self.collectionView reloadData];
}

#pragma mark - 内存泄露警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
